<template>
  <el-dialog
    :title="type === 'add' ? '新增客户' : '修改信息'"
    :visible.sync="value"
    append-to-body
    @close="close"
    @open="open"
    width="70%"
  >
    <el-steps :active="active" simple style="margin-bottom: 20px">
      <el-step title="基本信息" icon="el-icon-edit"></el-step>
      <el-step title="工商信息" icon="el-icon-upload"></el-step>
      <el-step title="结算户" icon="el-icon-picture"></el-step>
    </el-steps>
    <el-form v-if="active === 1" :model="baseForm" ref="baseform">
      <el-form-item
        :label="item.label"
        :prop="item.prop"
        v-for="(item, index) in baseFormDom"
        :key="index"
        :rules="item.rules"
        label-width="140px"
        class="custormer-width"
      >
        <el-select
          class="form-label"
          v-if="item.type === 'select'"
          v-model="baseForm[item.prop]"
        >
          <el-option
            v-for="(option, indexop) in item.dicData"
            :key="indexop"
            :label="option[item.props.label]"
            :value="option[item.props.value]"
          ></el-option>
        </el-select>
        <el-input
          class="form-label"
          v-else
          v-model="baseForm[item.prop]"
          :disabled="item.disabled"
        ></el-input>
      </el-form-item>
    </el-form>
    <el-form v-if="active === 2" :model="baseForm" ref="businessform">
      <el-form-item
        :label="item.label"
        :prop="item.prop"
        v-for="(item, index) in businessformDom"
        :key="index"
        :rules="item.rules"
        label-width="140px"
        class="custormer-width"
        :style="item.width && { width: item.width }"
      >
        <el-select
          class="form-label"
          v-if="item.type === 'select'"
          v-model="baseForm[item.prop]"
        >
          <el-option
            v-for="(option, indexop) in item.dicData"
            :key="indexop"
            :label="option[item.props.label]"
            :value="option[item.props.value]"
          ></el-option>
        </el-select>
        <el-cascader
          class="form-label"
          v-else-if="item.type === 'tree'"
          v-model="baseForm[item.prop]"
          :options="item.dicData"
          :props="item.props"
        ></el-cascader>
        <el-date-picker
          v-else-if="item.type === 'datetime'"
          v-model="baseForm[item.prop]"
          type="date"
          class="form-label"
          value-format="yyyy-MM-dd"
          format="yyyy-MM-dd"
          placeholder="选择日期时间"
        >
        </el-date-picker>
        <el-input
          class="form-label"
          v-else-if="item.type === 'inputmap'"
          v-model="baseForm[item.prop]"
          @focus="dialogVisible = true"
        ></el-input>
        <el-input
          class="form-label"
          v-else
          v-model="baseForm[item.prop]"
        ></el-input>
      </el-form-item>
    </el-form>
    <el-form v-if="active === 3" :model="baseForm" ref="settlementForm">
      <div
        class="account-border"
        v-for="(formItem, index) in baseForm.accountList"
        :key="index"
      >
        <el-form-item
          :label="`结算账户${index + 1}`"
          :prop="`accountList.${index}.accountNo`"
          :rules="[
            {
              required: true,
              message: '请输入结算账户',
              trigger: 'blur',
            },
          ]"
          label-width="140px"
          class="custormer-width"
        >
          <el-input class="form-label" v-model="formItem.accountNo"></el-input
        ></el-form-item>
        <el-form-item
          :label="`结算户名称${index + 1}`"
          :prop="`accountList.${index}.accountName`"
          :rules="[
            {
              required: true,
              message: '请输入结算户名称',
              trigger: 'blur',
            },
          ]"
          label-width="140px"
          class="custormer-width"
        >
          <el-input class="form-label" v-model="formItem.accountName"></el-input
          ><i
            v-if="index != 0"
            class="el-icon-remove-outline accountIcon"
            style="color: red"
            @click="deleteAccount(index)"
          ></i
        ></el-form-item>
        <el-form-item
          :label="`联系人`"
          :prop="`accountList.${index}.contactName`"
          :rules="[
            {
              required: true,
              message: '请输入联系人',
              trigger: 'blur',
            },
          ]"
          label-width="140px"
          class="custormer-width"
        >
          <el-input class="form-label" v-model="formItem.contactName"></el-input
        ></el-form-item>
        <el-form-item
          :label="`联系电话`"
          :prop="`accountList.${index}.contactMobile`"
          :rules="[
            {
              required: true,
              message: '请输入联系电话',
              trigger: 'blur',
            },
          ]"
          label-width="140px"
          class="custormer-width"
        >
          <el-input
            class="form-label"
            v-model="formItem.contactMobile"
          ></el-input
        ></el-form-item>
        <div
          v-for="(bank, bankindex) in formItem.bankInfoList"
          :key="bankindex"
        >
          <el-form-item
            :label="`缴费银行账户${bankindex + 1}`"
            :prop="`accountList.${index}.bankInfoList.${bankindex}.openBankName`"
            :rules="[
              {
                required: true,
                message: '请输入缴费银行账户',
                trigger: 'blur',
              },
            ]"
            label-width="140px"
            class="custormer-width"
          >
            <el-input class="form-label" v-model="bank.openBankName"></el-input
          ></el-form-item>
          <el-form-item
            :label="`缴费银行账户号${bankindex + 1}`"
            :prop="`accountList.${index}.bankInfoList.${bankindex}.bankNo`"
            :rules="[
              {
                required: true,
                message: '请输入缴费银行账户号',
                trigger: 'blur',
              },
            ]"
            label-width="140px"
            class="custormer-width"
          >
            <el-input class="form-label" v-model="bank.bankNo"></el-input>
            <i
              v-if="bankindex != 0"
              class="el-icon-remove-outline accountIcon"
              style="color: red"
              @click="deleteBank(index, bankindex)"
            ></i>
            <i
              v-if="bankindex === formItem.bankInfoList.length - 1"
              class="el-icon-circle-plus-outline accountIcon"
              style="color: green"
              @click="addBank(index)"
            ></i
          ></el-form-item>
        </div>
      </div>
      <div class="flex addCustorAccout flex-center" @click="addAccount">
        <i class="el-icon-plus"></i> 添加多个结算账户
      </div>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="close">取 消</el-button>
      <el-button v-if="active > 1" @click="active -= 1">上一步</el-button>
      <el-button type="primary" @click="gotoNext" :loading="submitloading">{{
        active === 3 ? "完成" : "下一步"
      }}</el-button>
    </span>
    <el-dialog
      title="点击地图，切换坐标点的位置"
      :visible.sync="dialogVisible"
      :width="`${
        (1920 - width) * 0.05 + 50 > 50 ? (1920 - width) * 0.05 + 50 : 50
      }%`"
      :before-close="handleClose"
      append-to-body
    >
      <changeAmap v-model="lampcenter" :center="center"></changeAmap>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="focusCenter">确 定</el-button>
      </span>
    </el-dialog>
  </el-dialog>
</template>

<script>
import request from "@/router/axios";
import changeAmap from "./changeAmap";
import { add, addSettlement, update } from "@/api/meter/customer";
import { getCustorList } from "@/api/meter/account";
export default {
  props: {
    value: {
      type: Boolean,
      default: false,
    },
    getInitData: {
      type: Function,
    },
    type: {
      type: Boolean,
    },
    editForm: {
      type: Object,
      default: {},
    },
  },
  data() {
    return {
      dialogVisible: false,
      width: 1920,
      lampcenter: [],
      center: [],
      active: 1,
      submitloading: false,
      baseForm: {},
      baseFormDom: [
        {
          label: "客户编号",
          prop: "customerNo",
          type: "input",
          disabled: true,
          rules: [
            {
              required: true,
              message: "请输入客户编号",
              trigger: "blur",
            },
          ],
        },
        {
          label: "所属行业",
          prop: "industryClass",
          type: "select",
          dicUrl: "/api/blade-system/dict-biz/dictionary?code=industry_class",
          props: {
            label: "dictValue",
            value: "dictKey",
          },
          rules: [
            {
              required: false,
              message: "请输入行业分类",
              trigger: "blur",
            },
          ],
        },
        {
          label: "客户名称",
          prop: "customerName",
          type: "input",
          rules: [
            {
              required: true,
              message: "请输入客户名称",
              trigger: "blur",
            },
          ],
        },
        {
          label: "负责人",
          prop: "contactName",
          rules: [
            {
              required: true,
              message: "请输入联系人姓名",
              trigger: "blur",
            },
          ],
        },
        {
          label: "联系电话",
          prop: "contactTel",
          rules: [
            {
              required: true,
              message: "请输入联系电话",
              trigger: "blur",
            },
          ],
        },
        {
          label: "客户类别",
          prop: "customerClass",
          type: "select",
          dicUrl: "/api/blade-system/dict-biz/dictionary?code=customer_class",
          props: {
            label: "dictValue",
            value: "dictKey",
          },
          rules: [
            {
              required: true,
              message: "请输入客户类型",
              trigger: "blur",
            },
          ],
        },
        {
          label: "客户经理",
          prop: "accountManager",
          rules: [
            {
              required: true,
              message: "请输入客户经理",
              trigger: "blur",
            },
          ],
        },
        {
          label: "备注信息",
          prop: "remarks",
          rules: [
            {
              required: false,
              message: "请输入备注信息",
              trigger: "blur",
            },
          ],
        },
      ],
      businessformDom: [
        {
          label: "公司名称",
          prop: "companyName",
          rules: [
            {
              required: false,
              message: "请输入公司名称",
              trigger: "blur",
            },
          ],
        },
        {
          label: "企业性质",
          prop: "customerType",
          type: "select",
          dicUrl: "/api/blade-system/dict-biz/dictionary?code=customer_type",
          props: {
            label: "dictValue",
            value: "dictKey",
          },
          rules: [
            {
              required: true,
              message: "请输入客户类型",
              trigger: "blur",
            },
          ],
        },
        {
          label: "企业注册地",
          prop: "regionId",
          // lazy: true,
          type: "tree",
          dicUrl: "/api/blade-system/region/tree",
          props: {
            label: "title",
            value: "id",
            leaf: "leaf",
            disabled: "disabled",
            emitPath: false,
          },
          rules: [
            {
              required: true,
              message: "请选择企业注册地",
              trigger: "blur",
            },
          ],
        },
        {
          label: "成立日期",
          prop: "establishedTime",
          type: "datetime",
          rules: [
            {
              required: false,
              message: "请输入成立日期",
              trigger: "blur",
            },
          ],
        },
        {
          label: "经度",
          prop: "longitude",
          type: "inputmap",
          rules: [
            {
              required: false,
              message: "请输入经度",
              trigger: "blur",
            },
          ],
        },
        {
          label: "纬度",
          prop: "latitude",
          type: "inputmap",
          rules: [
            {
              required: false,
              message: "请输入纬度",
              trigger: "blur",
            },
          ],
        },
        {
          label: "统一社会信用代码",
          prop: "unifiedSocialCreditCode",
          rules: [
            {
              required: false,
              message: "请输入统一社会信用代码",
              trigger: "blur",
            },
          ],
        },
        {
          label: "法人代表",
          prop: "legalPerson",
          rules: [
            {
              required: false,
              message: "请输入法人代表",
              trigger: "blur",
            },
          ],
        },
        {
          label: "详细地址",
          prop: "address",
          width: "100%",
          rules: [
            {
              required: false,
              message: "请输入详细地址",
              trigger: "blur",
            },
          ],
        },
        {
          label: "开户银行",
          prop: "bank",
          rules: [
            {
              required: false,
              message: "请输入开户银行",
              trigger: "blur",
            },
          ],
        },
        {
          label: "开户支行",
          prop: "accountOpeningBranch",
          rules: [
            {
              required: false,
              message: "请输入开户支行",
              trigger: "blur",
            },
          ],
        },
        {
          label: "开户名",
          prop: "openBankName",
          rules: [
            {
              required: false,
              message: "请输入开户名",
              trigger: "blur",
            },
          ],
        },
        {
          label: "银行账号",
          prop: "bankCardNumber",
          rules: [
            {
              required: false,
              message: "请输入银行账号",
              trigger: "blur",
            },
          ],
        },
      ],
    };
  },
  watch: {
    editForm(value) {
      for (let item in value) {
        if (typeof value[item] == "number") {
          value[item] = value[item].toString();
        }
      }
      this.baseForm = value;
    },
    "baseForm.longitude": {
      handler(val) {
        if (val) {
          this.lampcenter = [this.baseForm.longitude, this.baseForm.latitude];
          this.center = [this.baseForm.longitude, this.baseForm.latitude];
        } else {
          this.lampcenter = [116.400953, 39.911835];
          this.center = [116.400953, 39.911835];
        }
      },
    },
  },
  created() {
    const { baseFormDom, businessformDom, settlementDom } = this;
    let result = [];
    let list = [];
    let sendDic = (url) => {
      return request({
        url: url,
        method: "get",
      });
    };
    baseFormDom.forEach((ele, index) => {
      if (ele.dicUrl) {
        // 处理远程字典并加载
        list.push({
          type: "1",
          index: index,
        });
        result.push(
          new Promise(function (resolve) {
            sendDic(ele.dicUrl)
              .then((res) => {
                resolve(res.data);
              })
              .catch(() => {
                resolve([]);
              });
          })
        );
      }
    });
    businessformDom.forEach((ele, index) => {
      if (ele.dicUrl) {
        // 处理远程字典并加载
        list.push({
          type: "2",
          index: index,
        });
        result.push(
          new Promise(function (resolve) {
            sendDic(ele.dicUrl)
              .then((res) => {
                resolve(res.data);
              })
              .catch(() => {
                resolve([]);
              });
          })
        );
      }
    });
    Promise.all(result).then((data) => {
      list.forEach((item, num) => {
        if (item.type === "1") {
          this.$set(this.baseFormDom, item.index, {
            ...this.baseFormDom[item.index],
            dicData: data[num].data,
          });
        } else {
          this.$set(this.businessformDom, item.index, {
            ...this.businessformDom[item.index],
            dicData: data[num].data,
          });
        }
      });
    });
  },
  mounted() {
    this.width = document.body.clientWidth;
  },
  methods: {
    focusCenter() {
      // 选中经纬度
      const { lampcenter } = this;
      this.$set(this.baseForm, "longitude", lampcenter[0]);
      this.$set(this.baseForm, "latitude", lampcenter[1]);
      this.dialogVisible = false;
    },
    deleteBank(index, bankindex) {
      this.baseForm.accountList[index].bankInfoList.splice(bankindex, 1);
    },
    addBank(index) {
      this.baseForm.accountList[index].bankInfoList.push({
        bankNo: "",
        openBankName: "",
      });
    },
    deleteAccount(index) {
      this.baseForm.accountList.splice(index, 1);
    },
    addAccount() {
      this.baseForm.accountList.push({
        accountName: "",
        accountNo: "",
        bankInfoList: [
          {
            bankNo: "",
            openBankName: "",
          },
        ],
        contactMobile: "",
        contactName: "",
      });
    },
    open() {
      this.baseForm = {
        longitude: '',
        customerNo: (() => {
          let num = "";
          for (let i = 0; i < 20; i += 1) {
            num += Math.ceil(Math.random() * 9);
          }
          return num;
        })(),
        accountList: [
          {
            accountName: "",
            accountNo: "",
            bankInfoList: [
              {
                bankNo: "",
                openBankName: "",
              },
            ],
            contactMobile: "",
            contactName: "",
          },
        ],
      };
      this.active = 1;
    },
    close() {
      this.$emit("input", false);
    },
    gotoNext() {
      const { active, baseForm, settlementForm } = this;
      if (active === 1) {
        this.$refs.baseform.validate((valid) => {
          if (valid) {
            this.active += 1;
          }
        });
      } else if (active === 2) {
        this.$refs.businessform.validate((valid) => {
          if (valid) {
            this.active += 1;
          }
        });
      } else {
        // 结算户信息
        let ids = {};
        if (this.type === "edit") {
          ids.id = this.editForm.id;
        }
        this.$refs.settlementForm.validate((valid) => {
          if (valid) {
            this.submitloading = true;
            addSettlement({
              ...ids,
              ...baseForm,
              establishedTime: `${baseForm.establishedTime.split(' ')[0]} 00:00:00`,
            })
              .then((res) => {
                this.submitloading = false;
                this.$emit("input", false);
                this.getInitData();
                this.$message({
                  type: "success",
                  message: "操作成功",
                });
              })
              .catch(() => {
                this.submitloading = false;
              });
          }
        });
      }
    },
  },
  components: {
    changeAmap,
  },
};
</script>

<style lang="scss" scoped>
.custormer-width {
  display: inline-block;
  width: 50%;
  margin-right: 0;
  .form-label {
    width: 100%;
  }
}
.account-border {
  .form-label {
    width: 70%;
  }
}
.addCustorAccout {
  padding: 20px;
  border-top: 1px solid #e1e1e1;
  border-bottom: 1px solid #e1e1e1;
  color: #409eff;
  cursor: pointer;
}
.accountIcon {
  font-size: 30px;
  margin-left: 10px;
  vertical-align: middle;
}
.account-border {
  border-bottom: 1px solid #e1e1e1;
  padding-top: 20px;
}
</style>
